<script setup lang="ts">
import ConfigTable from "@/components/micro/ConfigTable.vue"
import {ref} from 'vue';
import {onMounted} from 'vue';
import {GetPatternDTO, AddPattern} from '@/api/micro';
import type {PatternDTO, PatternGraph} from '@/api/micro'
import {message} from 'ant-design-vue'
import {reactive} from 'vue'

const addPattern = reactive({
  name:'',
  desc:'',
  graph_data:''
})

const addNewPatternModalOpen = ref(false)

const openAddNewPatternModal = () => {
  addNewPatternModalOpen.value = true
}

const onCancelModal = () => {
  addNewPatternModalOpen.value = false
}

const onFinish = async (values: any) => {
  await onSubmitModal();
};

const onFinishFailed = (errorInfo: any) => {
  console.log('表单验证失败:', errorInfo);
  message.error('表单验证失败，请检查输入');
};

const onSubmitModal = async () => {
  try {
    // 验证 graph_data 是否可以正确解析为 PatternGraph
    try {
      const parsedGraphData = JSON.parse(addPattern.graph_data);
      // 验证解析后的对象是否符合 PatternGraph 结构
      if (!parsedGraphData.edges || !parsedGraphData.nodes || 
          !Array.isArray(parsedGraphData.edges) || !Array.isArray(parsedGraphData.nodes)) {
        throw new Error('JSON 格式不符合 PatternGraph 结构');
      }
    } catch (parseError) {
      message.error('调用模式格式错误，请检查 JSON 格式是否正确');
      return;
    }

    // 构造要发送的数据
    const patternData: PatternDTO = {
      name: addPattern.name,
      desc: addPattern.desc,
      graph_data: JSON.parse(addPattern.graph_data)  // 使用正确的字段名
    };

    // 打印请求参数 
    console.log('发送的请求参数:', JSON.stringify(patternData, null, 2));

    // 发送数据到后端
    const res = await AddPattern(patternData);
    
    if (res.code === 0) {
      message.success('配置添加成功');
      // 清空表单
      addPattern.name = '';
      addPattern.desc = '';
      addPattern.graph_data = '';
      // 关闭模态框
      addNewPatternModalOpen.value = false;
      // 刷新数据列表
      await getPatternDTO();
    } else {
      message.error(`添加失败: ${res.message}`);
    }
  } catch (error) {
    console.error('添加配置失败:', error);
    message.error('添加配置失败，请检查输入格式');
  }
};

interface DataItem {
  key: number;
  name: string;
  desc: string;
  pattern: string;
  // source: string;
  // svc_source: string;
  // target: string;
  // svc_target: string;
  // children?: DataItem[];
}

const pattern = ref<DataItem[]>([])

async function getPatternDTO() {
  const res = await GetPatternDTO();
  if (!res || !res.data || !Array.isArray(res.data)) {
    console.warn("PatternDTO 数据为空或格式错误:", res);
    pattern.value = [];
    return;
  }
  const dtoList: PatternDTO[] = res.data;
  const result: DataItem[] = [];
  let key = 0;
  for (const dto of dtoList) {
    result.push({
      key:  key++,
      name: dto.name,
      desc: dto.desc,
      pattern: JSON.stringify(dto.graph_data),
    })
    // const graph: PatternGraph = dto.graph_data;
    // const children: DataItem[] = [];
    // let target = "", svc_target = "";
    // for (const edge of graph.edges) {
    //   const sourceNode = graph.nodes.find(n => n.id === edge.source);
    //   const targetNode = graph.nodes.find(n => n.id === edge.target);
    //   target = edge.target
    //   svc_target = targetNode?.label.split('~/')[1] || ''
    //   children.push({
    //     key: key,
    //     name: dto.name,
    //     desc: dto.desc,
    //     label: edge.label,
    //     source: edge.source,
    //     svc_source: sourceNode?.label.split('~/')[1] || '',
    //     target: target,
    //     svc_target: svc_target,
    //   });
    // }
    // result.push({
    //   key: key++,
    //   name: dto.name,
    //   desc: dto.desc,
    //   label: graph.edges[0]?.label || '',
    //   source: graph.edges[0].source || '',
    //   svc_source: graph.nodes[0]?.label.split('~/')[1] || '',
    //   target: target,
    //   svc_target: svc_target,
    //   children: children,
    // });
  }
  pattern.value = result;
}

// 定期刷新
onMounted(() => {
  getPatternDTO(); // 初始加载
  setInterval(() => {
    getPatternDTO();
  }, 10000); // 每 10 秒刷新一次
});

</script>

<template>
  <div style="margin-left: 10px">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
      <a-button type="primary" @click="openAddNewPatternModal">+ 添加配置</a-button>
    </div>
    
    <ConfigTable :data="pattern"/>
    <a-button type="primary" @click="getPatternDTO">刷新</a-button>
  </div>
  <a-modal
    v-model:open="addNewPatternModalOpen"
    title="添加配置"
    :footer="null"
    width="600px"
  >
    <div>
      <a-form
        :model="addPattern"
        name="addPattern"
        :label-col="{span: 6}"
        :wrapper-col="{span: 14}"
        autocomplete="off"
        @submit="onFinish"
        @submitFailed="onFinishFailed"
      >
        <a-form-item
              label="名称"
              name="name"
              :rules="[{required: true, message: '请输入配置名称'}]"
            >
              <a-input v-model:value="addPattern.name"/>
            </a-form-item>
        <a-form-item
              label="描述"
              name="desc"
              :rules="[{required: true, message: '请输入配置描述'}]"
            >
              <a-input v-model:value="addPattern.desc"/>
            </a-form-item> 
        <a-form-item
              label="调用模式"
              name="graph_data"
              :rules="[{required: true, message: '请输入graphdata内容'}]"
            >
              <a-textarea style="overflow: auto" v-model:value="addPattern.graph_data"/>
            </a-form-item>
        <a-form-item :wrapper-col="{span: 14, offset:4}">
          <a-button type="primary" html-type="submit">提交</a-button>
          <a-button  style="margin-left: 10px" @click="onCancelModal">关闭</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>

</template>

<style scoped>

</style>

